Date.prototype.format = function(format) {
  let date = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3),
    "S+": this.getMilliseconds()
  };
  if (/(y+)/i.test(format)) {
    format = format.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (let k in date) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1
          ? date[k]
          : ("00" + date[k]).substr(("" + date[k]).length)
      );
    }
  }
  return format;
};

/**
 * 将GMT格式的时间转为数据库兼容的Date格式
 * gmt => GMT格式的时间
 * long => 是否长时间(包含时分秒)， 可不填(默认值：true), 选填：false
 * Wed Dec 01 2018 00:00:00 GMT+0800 (中国标准时间) => 2018-12-01 00:00:00 或 2018-12-01
 */
export function formatGMT(gmt, long) {
  long = false !== long;
  let date = new Date(gmt);

  let m = date.getMonth() + 1,
    mm = "-" + (m < 10 ? "0" + m : m);
  let d = date.getDate(),
    dd = "-" + (d < 10 ? "0" + d : d);
  let h = date.getHours(),
    hh = " " + (h < 10 ? "0" + h : h);
  let i = date.getMinutes(),
    ii = ":" + (i < 10 ? "0" + i : i);
  let s = date.getSeconds(),
    ss = ":" + (s < 10 ? "0" + s : s);

  return date.getFullYear() + mm + dd + (long ? hh + ii + ss : "");
}

export function getServerDatetime(callback) {
  let xhr;
  if (window.ActiveXObject) {
    //判断浏览器是否支持ActiveX控件
    //支持-通过ActiveXObject的一个新实例来创建XMLHttpRequest对象
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  } else if (window.XMLHttpRequest) {
    //不支持
    xhr = new XMLHttpRequest();
  }
  xhr.open("HEAD", location.href, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      let datetime = xhr.getResponseHeader("Date");
      callback(formatGMT(datetime));
    }
  };
  xhr.send(null);
}
